package com.web;

import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {
    //创建一个UserServiceImpl类的实例对象
    private UserService userService=new UserServiceImpl();

    /**
     * 重写获取post请求方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取post请求传来的参数
        String username = req.getParameter("username");//获取用户名
        String password = req.getParameter("password");//获取用户密码
        //String repwd = req.getParameter("repwd");
        String email = req.getParameter("email");//获取邮箱
        String code = req.getParameter("code");//获取验证码
        System.out.println("111");
        //2.检验验证码是否正确，这里先将验证码写死为“abcde”
        if ("abcde".equalsIgnoreCase(code)) {//忽略大小写
            //若验证码正确,判断用户名是否可用
            if (userService.existsUsername(username)) {

                //若用户名已存在,
                System.out.println("用户名["+username+"]已存在");
                //把回显信息保存到域中
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                //跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                //若用户名不存在，则保存到数据库
                userService.registUser(new User(null,username,password,email));
                //再跳转到注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
                System.out.println("用户注册成功");

            }
        }else {
            //若验证码不正确，
            System.out.println("验证码["+code+"]错误");
            //把回显信息保存到域中
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            //返回注册页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }

    }
}
